package me.obstsalat.guildera;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;

public class gt_villager_spawn extends TimerTask {
	private guildera plugin;
	
	gt_villager_spawn(guildera pl) {
		plugin = pl;
	}

	@Override
	public void run() {
		for(guild g : plugin.guilds) {
			long max_npcs = (long)(g.getArea() * plugin.config.getDouble("max_villager_factor"));
			long current_npcs = 0;
			for(Entity ent : plugin.overworld.getEntities()) {
				if(ent.getType() == EntityType.VILLAGER && g.isInGuild(ent.getLocation())) {
					current_npcs++;
				}
			}
			int points = 0;
			List<Location2d> done = new ArrayList<Location2d>();
			for(Location2d l2d : g.getAreaList()) {
				boolean cont = true;
				for(Location2d check : done) {
					if(check.equal(l2d)) {
						cont = false;
					}
				}
				if(cont) {
					for(int dx = -1; dx <= 1; dx++) {
						for(int dz = -1; dz <= 1; dz++) {
							int y = 1;
							do {
								boolean found = false;
								for(int dy = 0; dy <= 3; dy++) {
									int id = plugin.overworld.getBlockTypeIdAt(l2d.getX() + dx, y + dy, l2d.getZ() + dz);
									if(!found && (id == 26 || id == 64 || id == 71)) {
										int c = 0;
										for(int ny = 2; ny <= 12; ny++) {
											id = plugin.overworld.getBlockTypeIdAt(l2d.getX() + dx, y + dy + ny, l2d.getZ() + dz);
											c = c + id;
										}
										if(c > 0) {
											found = true;
										}
									}
								}
								if(found) {
									points++;
								}
								y = y + 4;
							}while(y <= 250);
						}
					}
				}
			}
			if(current_npcs < max_npcs && points > 15) {
				if(Math.random() < (points/max_npcs) && plugin.overworld.getBlockAt(g.getPosition()).getLightLevel() > 7) {
					plugin.overworld.spawnCreature(g.getTeleport(), EntityType.VILLAGER);
				}
			}
		}
	}
	
	
}
